package com.thatvn.diemtinvietnam;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;

public class jsonParseCategory {	  
	   private String catname = "catname";	   
	   private String link = "link";
	   private String urlString = "";	  
	   
	   public volatile boolean parsingComplete = true;
	   public ArrayList<HashMap<String, String>> itemNewsListCategory;
	   
	   public jsonParseCategory(String url){
	      this.urlString = url;
	   }
	   
	   public ArrayList<HashMap<String, String>> getItemNewsListCategory(){
		   return itemNewsListCategory;
	   }
	  
	   
	   @SuppressLint("NewApi")
	   public void readAndParseJSON(String in) {
		  JSONArray items = null; 
		  //String preTitle="";
	      try {
	    	  JSONObject jsonObj = new JSONObject(in);
         
           // Getting JSON Array node
	    	  items = jsonObj.getJSONArray("news");	    	  
	    	 
	    	  itemNewsListCategory = new ArrayList<HashMap<String, String>>();
	    	 
	    	  //String preTitle="";
	    	  
		         for (int i = 0; i < items.length(); i++) {		             
		             try{
			           	  JSONObject c = items.getJSONObject(i);
			              if (c.isNull("catname")) continue;		                 
				          catname=  c.getString("catname"); 			                
				          link=c.getString("link"); 
				          HashMap<String, String> itemDetail = new HashMap<String, String>();
				          itemDetail.put("catname", catname);		                  
		                  itemDetail.put("link", link);
		                  itemNewsListCategory.add(itemDetail);
		             }catch(Exception ex)
		             {
		           	  //Log.e("ExceptionExceptionExceptionExceptionExceptionException", ex.toString());
		             }
		         }//for
		         	parsingComplete = false;
	        } catch (Exception e) {
	           // TODO Auto-generated catch block
	        	//Log.e("ExceptionExceptionExceptionExceptionExceptionException", e.toString());
	           e.printStackTrace();
	        }

	   }
	   public String fetchJSON() throws IOException{
	      
	         try {
	            URL url = new URL(urlString);
	            //Log.e("fetchJSON", urlString);
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            conn.setReadTimeout(10000 /* milliseconds */);
	            conn.setConnectTimeout(15000 /* milliseconds */);
	            conn.setRequestMethod("GET");
	            conn.setDoInput(true);
	            //conn.setRequestProperty(field, newValue)
	            // Starts the query
	            conn.connect();
	            //Log.e("fetchJSON", "ok1");
		         //InputStream stream = conn.getInputStream();
	            InputStreamReader reader = null;
		         StringBuilder builder = new StringBuilder();
	
		         try {
		             // ...
		             reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
		             char[] buffer = new char[8192];
	
		             for (int length = 0; (length = reader.read(buffer)) > 0;) {
		                 builder.append(buffer, 0, length);
		                 
		             }
		         } finally {
		             if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
		         }
	
		         String html = builder.toString();
		         
		         String data = html;//convertStreamToString(stream);
	      		 data="{\"news\":"+data+"}";
	      		 //Log.e("fetchJSON", data);
	      		 readAndParseJSON(data);
	      		 //stream.close();
	      		 return data;
	         } catch (Exception e) {
	            e.printStackTrace();
	            return "0";
	         }	         
	      		
	   }
	   static String convertStreamToString(java.io.InputStream is) {
	      java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
	      return s.hasNext() ? s.next() : "";
	   }
}
